package com.hengtongxing.hejiayun.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.google.android.flexbox.FlexboxLayout;
import com.hengtongxing.hejiayun.R;
import com.hengtongxing.hejiayun.base.DataCallBack;
import com.hengtongxing.hejiayun.bean.BaseResponseBean;
import com.hengtongxing.hejiayun.bean.ShopCartListBean;
import com.hengtongxing.hejiayun.bean.ShopDetailsBean;
import com.hengtongxing.hejiayun.shop.ShopConfirmOrderActivity;
import com.hengtongxing.hejiayun.shop.model.ShopModelImpl;
import com.hengtongxing.hejiayun.utils.DisplayUtil;
import com.hengtongxing.hejiayun.utils.Dp2Px;
import com.hengtongxing.hejiayun.utils.FastClickUtils;
import com.hengtongxing.hejiayun.utils.GlideUtils;
import com.hengtongxing.hejiayun.utils.NumberFormatUtils;
import com.hengtongxing.hejiayun.utils.ToastUtil;
import com.makeramen.roundedimageview.RoundedImageView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 *
 */
public class ShopCartDialog extends DialogFragment {


    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.iv_picture)
    RoundedImageView ivPicture;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_integral_price)
    TextView tvIntegralPrice;
    @BindView(R.id.tv_market_price)
    TextView tvMarketPrice;
    @BindView(R.id.ll_sort)
    RelativeLayout llSort;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.ll_add)
    RelativeLayout llAdd;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.dialog_layout)
    LinearLayout dialogLayout;
    @BindView(R.id.flex_search_hot)
    FlexboxLayout flexSearchHot;
    private Dialog dialog;
    Unbinder unbinder;
    private Context mContext;
    private ShopDetailsBean.DataBean itemListBean;
    private int type;
    private TextView chooseView;
    private ShopDetailsBean.DataBean.GoodsNormBean chooseNormBean;
    private OnCallBackListener onCallBackListener;

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_shop_cart, null);
        unbinder = ButterKnife.bind(this, view);
        mContext = getActivity();
        initView();
        return view;
    }

    public static ShopCartDialog newInstance(int type, ShopDetailsBean.DataBean itemListBean) {
        Bundle args = new Bundle();
        ShopCartDialog fragment = new ShopCartDialog();
        args.putSerializable("itemListBean", itemListBean);
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    //    初始化请求
    private void initView() {
        type = getArguments().getInt("type", 0);
        itemListBean = (ShopDetailsBean.DataBean) getArguments().getSerializable("itemListBean");
        if (type == 2) {
            tvCommit.setText("立即购买");
        } else {
            tvCommit.setText("确定");
        }

        if (itemListBean != null) {
            GlideUtils.loadImage(mContext, ivPicture, itemListBean.getThumb());
            String money = NumberFormatUtils.formatDouble(Double.parseDouble(itemListBean.getPrice()) / 100);
            tvMarketPrice.setText(money);
            tvTitle.setText(itemListBean.getName());

            requestHot(itemListBean.getGoods_norm());

        }
    }

    /**
     * 商品规格
     */
    public void requestHot(List<ShopDetailsBean.DataBean.GoodsNormBean> mList) {
        flexSearchHot.removeAllViews();
        for (ShopDetailsBean.DataBean.GoodsNormBean normBean : mList) {
            flexSearchHot.addView(getFlexView(normBean));
        }
    }

    private TextView getFlexView(ShopDetailsBean.DataBean.GoodsNormBean normBean) {

        TextView tv = new TextView(mContext);
        tv.setText(normBean.getNorm());
        tv.setTextSize(14);
        tv.setTextColor(getResources().getColor(R.color.text_color_2));
        int padding = (int) Dp2Px.dp2Px(14);
        tv.setPadding(padding, 0, padding, 0);
        tv.setGravity(Gravity.CENTER);
        tv.setBackgroundResource(R.drawable.shape_search_tv);

        FlexboxLayout.LayoutParams params = new FlexboxLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,//
                ViewGroup.LayoutParams.WRAP_CONTENT);

        int marginRight = (int) Dp2Px.dp2Px(13);
        int marginTop = (int) Dp2Px.dp2Px(13);
        params.setMargins(0, marginTop, marginRight, 0);

        tv.setLayoutParams(params);
        tv.setTag(normBean);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseNormBean = (ShopDetailsBean.DataBean.GoodsNormBean) v.getTag();
                v.setBackgroundResource(R.drawable.shape_search_choose_tv);
                if (chooseView != null) {
                    chooseView.setBackgroundResource(R.drawable.shape_search_tv);
                }
                chooseView = (TextView) v;

                String money = NumberFormatUtils.formatDouble(Double.parseDouble(chooseNormBean.getPrice()) / 100);
                tvMarketPrice.setText(money);
            }
        });
        return tv;
    }

    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = DisplayUtil.getScreenHeight() / 3 * 2;
        lp.gravity = Gravity.BOTTOM;
        window.getAttributes().windowAnimations = R.style.commomDialog;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    @OnClick({R.id.iv_close, R.id.tv_commit, R.id.ll_sort, R.id.ll_add})
    public void onViewClicked(View view) {
        if (FastClickUtils.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_close:
                dismiss();
                break;
            case R.id.tv_commit:
                if (chooseNormBean == null) {
                    ToastUtil.showShort("请选择商品规格");
                    return;
                }
                String number = tvNumber.getText().toString();
                if (type == 1) {
                    requestShopCartAdd(itemListBean.getId() + "", chooseNormBean.getId() + "", number);
                }
                if (type == 2) {

                    List<ShopCartListBean.DataBean.ItemListBean> mList = new ArrayList<>();
                    ShopCartListBean.DataBean.ItemListBean itemBean = new ShopCartListBean.DataBean.ItemListBean();
                    itemBean.setMid(itemListBean.getMid());
                    itemBean.setGoods_id(itemListBean.getId());
                    itemBean.setPrice(chooseNormBean.getPrice());
                    itemBean.setThumb(chooseNormBean.getPic());
                    itemBean.setType(itemListBean.getType());
                    itemBean.setName(itemListBean.getName());
                    itemBean.setNum(Integer.parseInt(number));
                    itemBean.setNorm_id(chooseNormBean.getId());
                    ShopCartListBean.DataBean.ItemListBean.NormBean normBean = new ShopCartListBean.DataBean.ItemListBean.NormBean();
                    normBean.setId(chooseNormBean.getId());
                    normBean.setNorm(chooseNormBean.getNorm());
                    normBean.setPrice(chooseNormBean.getPrice());
                    normBean.setPic(chooseNormBean.getPic());
                    itemBean.setNorm(normBean);
                    mList.add(itemBean);
                    Intent intent = new Intent(mContext, ShopConfirmOrderActivity.class);
                    intent.putExtra("itemList", (Serializable) mList);
                    intent.putExtra("type", "order");
                    startActivity(intent);
                }
                dismiss();

                break;
            case R.id.ll_sort:
                int num = Integer.parseInt(tvNumber.getText().toString());
                if (num > 1) {
                    num--;
                }
                tvNumber.setText(String.valueOf(num));
                break;
            case R.id.ll_add:
                num = Integer.parseInt(tvNumber.getText().toString());
                num++;
                tvNumber.setText(String.valueOf(num));
                break;
        }
    }

    public void requestShopCartAdd(String goods_id, String norm_id, String num) {
        new ShopModelImpl().requestIntegralShopCartAdd(goods_id, norm_id, num, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("添加成功");
                onCallBackListener.onCallBack(1);
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public interface OnCallBackListener {
        void onCallBack(int type);
    }
}
